package com.mtsmda.test.comanda.d;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class ReadArrayFromFile {

	public static void main(String[] args) {

		String fileName = System.getProperty("user.dir")
				+ java.io.File.separator + "array.txt";
		readFile(fileName);
	}

	public static StringBuilder readFile(String fileName) {
		StringBuilder builder = new StringBuilder();
		try {
			int ar[][] = null;
			boolean first = true;
			List<String> readAllLines = Files.readAllLines(Paths.get(fileName));
			System.out.println("Simple variant");
			builder.append(DirectoryTree.ENTER).append("Simple variant")
					.append(DirectoryTree.ENTER);
			int currentSubArray = 0;
			for (String line : readAllLines) {
				System.out.println(line);
				builder.append(line);
				String[] split = line.split("[\\s]");

				if (first) {
					first = false;
					ar = new int[split.length][split.length];
				}
				writeDateInStringToArrayInt(split, ar, currentSubArray);
				currentSubArray++;
			}
			System.out.println("Unwrapped variant");
			builder.append(DirectoryTree.ENTER).append("Unwrapped variant")
					.append(DirectoryTree.ENTER);
			builder.append(showArrayUnwrapped(ar));
		} catch (Exception e) {
			System.out.println(e.getMessage());
			builder.append("ERROR - ").append(e.getMessage());
		}
		return builder;
	}

	private static void writeDateInStringToArrayInt(String[] split, int ar[][],
			int currentSubArray) {
		if (split != null && split.length > 0) {
			for (int i = 0; i < split.length; i++) {
				String currentString = split[i];
				int parseInt = -1;
				try {
					parseInt = Integer.parseInt(currentString);
				} catch (Exception e) {
					parseInt = 0;
				}
				ar[currentSubArray][i] = parseInt;
			}
		}
	}

	private static StringBuilder showArrayUnwrapped(int ar[][]) {
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < ar.length; i++) {
			for (int j = 0; j < ar[i].length; j++) {
				System.out.print("ar[" + i + "][" + j + "] = " + ar[i][j]
						+ "\t");
				builder.append("ar[").append(i).append("][").append(j)
						.append("] = ").append(ar[i][j])
						.append(DirectoryTree.TAB);
			}
			System.out.println();
			builder.append(DirectoryTree.ENTER);
		}
		return builder;
	}

}